from django.contrib.gis.db import models
from django.contrib.gis.models import SpatialRefSys
from django.utils.translation import ugettext_lazy as _
from django.template import loader, Context
from django.conf import settings
from dataset import DataSet, DataType, DataFormat
from meta import Keyword

class Layer(models.Model):
	__module__ = 'duetopia.register.models'
	dataType = models.ForeignKey(DataType, verbose_name=_('type'))
	name = models.CharField(max_length=255, verbose_name=_('name'))
	title = models.CharField(max_length=255, verbose_name=_('title'))
	notes = models.TextField(max_length=16384, blank=True, null=True, verbose_name=_('notes'))
	dataset = models.ForeignKey(DataSet, verbose_name=_('data set'))
	srs = models.ManyToManyField(SpatialRefSys, verbose_name=_('spatial reference systems'))
	keywords = models.ManyToManyField(Keyword, verbose_name=_('keywords'))
	extents = models.PolygonField(null=True, verbose_name=_('extents'))
	thumbnail_format = models.ForeignKey(DataFormat, null=True, blank=True, verbose_name=_('thumbnail format'))
	objects = models.GeoManager()
	class Admin:
		list_display = ('dataset', 'name', 'title_utf8', 'dataType')
		list_display_links = ('name',)
		search_fields = ('name', 'title', 'dataset__name')
	class Meta:
		verbose_name = _('layer')
		verbose_name_plural = _('layers')
		unique_together = (('dataset', 'name'),)
		ordering = ('name',)
	def __str__(self):
		return self.name

	geometry = "extents"
	def get_kml_url(self):
		return "/duetopia/feature/register/layer/%s.kml" % self.id
	def pextents(self):
		t = loader.get_template("register/list_map.html")
		return t.render(Context({ "object" : self }))
	pextents.allow_tags = True
	pextents.short_description = _("envelope")
	
	def get_absolute_url(self):
		return '/duetopia/register/layer/%s/' % (self.id,)

	def title_utf8(self):
		"for some reason django breaks on utf8 in database"
		return unicode.encode(self.title, 'utf-8')
	title_utf8.short_description = _('title')

	@property
	def thumbnail_file(self):
		from os import makedirs, path, stat
		dirname = path.join(settings.REGISTER_THUMBNAIL_DIR, str(self.dataset.id))
		try: stat(dirname)
		except: makedirs(dirname)
		if not self.thumbnail_format:
			raise ValueError('no format')
		return path.join(dirname, '%s.%s' % (self.name, self.thumbnail_format.extension))
	@property
	def thumbnail(self):
		fp = open(self.thumbnail_file, 'r')
		data = fp.read()
		fp.close()
		return data

class LayerStyle(models.Model):
	__module__ = 'duetopia.register.models'
	layer = models.ForeignKey(Layer, related_name='style_set', verbose_name=_('layer'))
	name = models.CharField(max_length=64, verbose_name=_('name'))
	title = models.CharField(max_length=256, verbose_name=_('title'))
	class Meta:
		verbose_name = _('data style')
		verbose_name_plural = _('data styles')
		unique_together = (('layer', 'name'),)

